/*
 * Copyright (c) 2019-2020, https://api.iot.10086.cn/(https://gitee.com/cmcc-iot-api/iot-card-open-application/).
 */
package cn.iot.card.open.terminal.controller;

import cn.iot.card.open.annotion.Permission;
import cn.iot.card.open.constants.Constants;
import cn.iot.card.open.context.LoginContextHolder;
import cn.iot.card.open.context.model.LoginUser;
import cn.iot.card.open.exception.enums.BizExceptionEnum;
import cn.iot.card.open.modular.entity.AccountCard;
import cn.iot.card.open.modular.entity.Card;
import cn.iot.card.open.modular.entity.UserGroupRl;
import cn.iot.card.open.modular.log.ApiBussinessLog;
import cn.iot.card.open.modular.service.AccountCardService;
import cn.iot.card.open.modular.service.CardService;
import cn.iot.card.open.modular.service.GroupService;
import cn.iot.card.open.modular.service.UserService;
import cn.iot.card.open.pojo.page.LayuiPageFactory;
import cn.iot.card.open.terminal.dto.BlankSmsDTO;
import cn.iot.card.open.terminal.dto.SmsSendRecordDTO;
import cn.iot.card.open.terminal.dto.TemplateSmsDTO;
import cn.iot.card.open.terminal.service.SmsSendService;
import cn.iot.card.open.terminal.warpper.SmsSendWrapper;
import cn.iot.card.open.util.CommonUtil;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 短信下发
 *
 * @author cmcc-iot-api
 * @date 20201026 14:11:04
 */
@Controller
@RequestMapping("/terminalCtrl/smsSend")
@Slf4j
public class SmsSendController {

    /**
     * 短信下发页面路径地址前缀
     */
    private static String PREFIX = "/modular/terminal/smsSend";

    @Autowired
    private CardService cardService;

    @Autowired
    private UserService userService;

    @Autowired
    private GroupService groupService;

    @Autowired
    private AccountCardService accountCardService;

    @Autowired
    private SmsSendService smsSendService;

    /**
     * 跳转到短信下发查询列表页面
     *
     * @return 返回 string
     * @author cmcc-iot-api
     * @date 20201026 14:13:35
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/smsSend.html";
    }

    /**
     * 查询短信下发记录
     *
     * @param smsSendRecordDTO
     * @return 返回 object
     * @throws Exception
     * @author cmcc-iot-api
     * @date 20201026 14:29:11
     */
    @Permission
    @RequestMapping("/list")
    @ResponseBody
    public Object list(SmsSendRecordDTO smsSendRecordDTO) throws Exception {
        String transId = CommonUtil.generateTransId(null);
        log.info("[{}] start get sms send list.", transId);
        long startTime = System.currentTimeMillis();
        LoginUser loginUser = LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = groupService.getUserGroupRlByUserId(loginUser.getId());
        // 如果当前用户未绑定卡组，则返回空（也可以提示错误）
        if (null == userGroupRl) {
            log.info("[{}] get sms send list end, cost: {}ms.", transId, System.currentTimeMillis() - startTime);
            return LayuiPageFactory.createEmptyPageInfo();
//            return LayuiPageFactory.createBizExceptionMsg(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }

        String msisdn = smsSendRecordDTO.getMsisdn();
        List<Card> cardInGroups = cardService.findCardInGroup(userGroupRl.getGroupId().toString(),
                Constants.CARD_TYPE_MSISDN, StringUtils.isBlank(msisdn) ? null : msisdn);

        // 如果当前用户绑定的卡组下面没有任何卡，则返回空（也可以提示错误）
        if (ToolUtil.isEmpty(cardInGroups)) {
            log.info("[{}] get sms send list end, cost: {}ms.", transId, System.currentTimeMillis() - startTime);
            return LayuiPageFactory.createEmptyPageInfo();
            //            return LayuiPageFactory.createBizExceptionMsg(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }
        String[] msisdns = new String[cardInGroups.size()];
        int cardNum = 0;
        for (Card card : cardInGroups) {
            msisdns[cardNum] = card.getMsisdn();
            cardNum ++;
        }

        Page<Map<String, Object>> accounts = smsSendService.selectSmsSendRecord(msisdns, smsSendRecordDTO);
        Page wrapped = new SmsSendWrapper(accounts).wrap();
        log.info("[{}] get sms send list end, cost: {}ms.", transId, System.currentTimeMillis() - startTime);
        return LayuiPageFactory.createPageInfo(wrapped);

    }

    /**
     * 跳转发送下行模板短信页面
     *
     * @return 返回 string
     * @author zhanlele
     * @date 20200225 21:12:45
     * @modify 20200225 zhanlele v1.1 创建
     * @since v1.1
     */
    @RequestMapping("/toTemplateSmsPage")
    public String toSendDownTemplateSmsPage() {
        return PREFIX + "/templateSms.html";
    }

    /**
     * 发送下行模板短信
     *
     * @return 返回 response data
     * @author zhanlele
     * @date 20200226 09:37:05
     * @modify 20200226 zhanlele v1.1 创建
     * @since v1.1
     */
    @RequestMapping("/sendTemplateSms")
    @ApiBussinessLog(value = "发送下行模板短信")
    @ResponseBody
    public ResponseData sendTemplateSms(TemplateSmsDTO templateSmsDTO) throws Exception {
        String msisdns = templateSmsDTO.getMsisdns();
        Card card = cardService.verifyCardInfo(msisdns, null, null);
        if (null == card) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_EXIT_IN_SYSTEM);
        }

        // 卡号未校验错误
        if (card.getCheckResult().intValue() == Constants.CARD_CHECK_RESULT_UNCHECKED.intValue()) {
            throw new ServiceException(BizExceptionEnum.CARD_CHECK_NULL);
        }

        // 卡号校验未通过错误
        if (card.getCheckResult().intValue() == Constants.CARD_CHECK_RESULT_NOPASS.intValue()) {
            throw new ServiceException(BizExceptionEnum.CARD_CHECK_ERROR);
        }

        LoginUser loginUser = LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = userService.getUserGroupRlByUserAndCard(loginUser.getId(), card.getCardId());
        if (null == userGroupRl) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }

        AccountCard accountCard = accountCardService.getBaseMapper().findByCardId(card.getCardId());
        String accountId = String.valueOf(accountCard.getAccountId());
        String transId = CommonUtil.generateTransId(accountId);
        return smsSendService.sendTemplateSms(transId, accountId, templateSmsDTO);
    }

    /**
     * 跳转发送下行空短信页面
     *
     * @return 返回 string
     * @author zhanlele
     * @date 20200225 21:41:01
     * @modify 20200225 zhanlele v1.1 创建
     * @since v1.1
     */
    @RequestMapping("/toBlankSmsPage")
    public String toSendDownBlankSmsPage() {
        return PREFIX + "/blankSms.html";
    }

    /**
     * 发送下行空短信
     *
     * @return 返回 response data
     * @author zhanlele
     * @date 20200226 09:38:07
     * @modify 20200226 zhanlele v1.1 创建
     * @since v1.1
     */
    @RequestMapping("/sendBlankSms")
    @ApiBussinessLog(value = "发送下行空短信")
    @ResponseBody
    public ResponseData sendBlankSms(BlankSmsDTO blankSmsDTO) throws Exception {
        String msisdns = blankSmsDTO.getMsisdns();
        Card card = cardService.verifyCardInfo(msisdns, null, null);
        if (null == card) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_EXIT_IN_SYSTEM);
        }

        // 卡号未校验错误
        if (card.getCheckResult().intValue() == Constants.CARD_CHECK_RESULT_UNCHECKED.intValue()) {
            throw new ServiceException(BizExceptionEnum.CARD_CHECK_NULL);
        }

        // 卡号校验未通过错误
        if (card.getCheckResult().intValue() == Constants.CARD_CHECK_RESULT_NOPASS.intValue()) {
            throw new ServiceException(BizExceptionEnum.CARD_CHECK_ERROR);
        }

        LoginUser loginUser = LoginContextHolder.getContext().getUser();
        UserGroupRl userGroupRl = userService.getUserGroupRlByUserAndCard(loginUser.getId(), card.getCardId());
        if (null == userGroupRl) {
            throw new ServiceException(BizExceptionEnum.CARD_NOT_BELONG_USER);
        }

        AccountCard accountCard = accountCardService.getBaseMapper().findByCardId(card.getCardId());
        String accountId = String.valueOf(accountCard.getAccountId());
        String transId = CommonUtil.generateTransId(accountId);

        return smsSendService.sendBlankSms(transId, accountId, blankSmsDTO);
    }
}
